<template>
  <!-- 报名名单列表 -->
  <a-card :bordered="false" class="br-10">
    <a-spin :spinning="loading" tip="Loading...">
      <div v-if="!inviteAppUserInfoId" class="table-operator">
        <a-button type="primary" ghost @click="handleAdd()">新增报名</a-button>
        <!-- 暂时隐藏1007的代用户报名 -->
        <a-button v-if="tenantId && tenantId != 1007" type="primary" ghost @click="handleBatchModule">
          选用户代报名
        </a-button>
        <a-button type="primary" ghost @click="handleImportRegistration">导入代报名名单</a-button>
        <!-- <a-button type="primary" ghost @click="handleUpdateAttendanceCard">更新参会证</a-button> -->
      </div>
      <div class="new-page-search _mb-16">
        <a-form>
          <a-row
            type="flex"
            justify="start"
            align="middle"
            :gutter="[
              { sm: 10, lg: 20, xl: 30, xxl: 40 },
              { lg: 4, xxl: 12 }
            ]"
          >
            <a-col :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="关键词">
                <a-input v-model="queryParam.keyWord" placeholder="姓名、单位、会员职务、手机号搜索" allowClear />
              </a-form-item>
            </a-col>
            <a-col :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="报名人员类型">
                <a-select v-model="queryParam.identity" placeholder="请选择报名人员类型" allowClear>
                  <a-select-option
                    v-for="dict in Dict.getLocal('identityDict')"
                    :key="dict.dictValue"
                    :value="dict.dictValue"
                  >
                    {{ dict.dictLabel }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="报名类型">
                <a-select
                  v-model="queryParam.activityTicketId"
                  placeholder="请选择报名类型"
                  allowClear
                  class="min-width-15"
                >
                  <a-select-option v-for="item in ticketList" :key="item.value" :value="item.id">{{
                    item.ticketName
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="报名来源">
                <a-select
                  v-model="queryParam.registerType"
                  placeholder="请选择报名来源"
                  allowClear
                  class="min-width-15"
                >
                  <a-select-option v-for="item in registerTypeList" :key="item.value" :value="item.value">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col v-if="!approvalStatus" :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="报名状态">
                <a-select v-model="queryParam.approvalStatus" placeholder="请选择报名状态" allowClear>
                  <a-select-option
                    v-for="dict in Dict.getLocal('rosterApprovalStatusDict')"
                    :key="dict.dictValue"
                    :value="dict.dictValue"
                  >
                    {{ dict.dictLabel }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col v-if="signStatus === undefined" :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="签到状态">
                <a-select v-model="queryParam.signStatus" placeholder="请选择签到状态" allowClear>
                  <a-select-option v-for="item in signStatusOptions" :key="item.value" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="参会者标签">
                <a-select
                  v-model="queryParam.labelIds"
                  mode="multiple"
                  placeholder="请选择参会者标签进行筛选"
                  allowClear
                  class="min-width-20"
                >
                  <a-select-option v-for="item in label_list" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col v-if="activityInfo.activityType !== activityTypeEnum.other_join" :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="来源组织">
                <a-select
                  v-model="queryParam.sourceTenantId"
                  placeholder="请选择来源组织"
                  allowClear
                  style="width: 150px;"
                >
                  <a-select-option v-for="item in organizationList" :key="item.tenantId" :value="item.tenantId">
                    {{ item.orgName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="手机号为空">
                <a-checkbox v-model="queryParam.isNullPhone"></a-checkbox>
              </a-form-item>
            </a-col>
            <a-col :sm="24" :xxl="12">
              <a-form-item label="信息收集表">
                <SelectCustomForm :activityId="activityId" ref="SelectCustomForm" />
              </a-form-item>
            </a-col>
            <a-col :sm="24" :lg="12" :xl="8" :xxl="6">
              <a-button type="primary" @click="refresh">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div v-if="total" class="table-operator disFlxJS">
        <div class="disFlxAC">
          <a-button type="primary" ghost @click="exportTable">导出筛选名单</a-button>
        </div>
        <div>
          <a-button type="primary" v-if="!disableOption" ghost @click="handleBathCancelRigster">批量取消报名</a-button>
          <a-button type="primary" ghost @click="handleSetLabel">批量打标签</a-button>
          <SendMessageSelect :dataSource="DataSourceEnum.REGISTERLIST" :objectId="activityId" />
          <a-button
            v-if="activityInfo.activityType !== activityTypeEnum.other_join"
            type="primary"
            ghost
            @click="handlePrintBadgeBatch"
            >批量打印胸卡</a-button
          >
          <a-button v-if="!approvalStatus || approvalStatus == 1" type="primary" @click="handleBathExamine">
            批量审核
          </a-button>
        </div>
      </div>

      <s-table
        size="default"
        ref="table"
        rowKey="id"
        :columns="newColumns"
        :data="loadData"
        :scroll="{ x: 2100, y: 720 }"
      >
        <!-- 序号 -->
        <span slot="serial" slot-scope="text, record, index">
          {{ (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1 }}
        </span>

        <!-- 报名者信息 -->
        <div slot="personInfo" slot-scope="text, record">
          <div class="disFlxAC flexCenter" style="flex-wrap: nowrap;">
            <span class="ov-1 _mr-4">{{ record.personName }}</span>
            <UserIconAction v-if="isOneself" :appUserInfoId="record.appUserInfoId"></UserIconAction>
          </div>
          <div>{{ record.personTel }}</div>
        </div>
        <!-- 单位信息 -->
        <div slot="companyInfo" slot-scope="text, record">
          <a-tooltip :title="record.companyName">
            <div class="w-[200px] ov-1">{{ record.companyName }}</div>
          </a-tooltip>
          <div v-if="record.companyPosition" class="companyInfoTag">{{ record.companyPosition }}</div>
        </div>
        <!-- 身份信息 -->
        <div slot="sourceInfo" slot-scope="text, record" class="disFlxAC flexCol">
          <a-tooltip :title="record.orgName">
            <div class="w-[120px] ov-1" style="text-align: left;">{{ record.orgName }}</div>
          </a-tooltip>
          <div class="disFlxAC" style="margin-top: 3px;">
            <a-tooltip v-if="record.memberId" :title="record.memberLevelName">
              <a-tag color="orange" style="margin: 0;">
                <div class="ov-1">{{ record.memberLevelName }}</div>
              </a-tag>
            </a-tooltip>
            <SetMember
              v-if="isOneself && !record.memberId && record.appUserInfoId"
              :appUserInfoId="record.appUserInfoId"
              :registerId="record.id"
              :memberLevelOption="memberLevelOption"
              @refresh="refresh(false, 'emit')"
            ></SetMember>
          </div>
        </div>
        <!-- 类型名称 -->
        <div slot="ticketName" slot-scope="text, record">
          <a-tooltip v-if="record.ticketName" :title="record.ticketName">
            <a-tag :color="record.ticketType === TicketTypeEnum.pay ? 'red' : ''">
              <div class="ov-1">{{ record.ticketName }}</div>
            </a-tag>
          </a-tooltip>
          <span v-else>--</span>
        </div>
        <!-- 实付金额 -->
        <div slot="payMoney" slot-scope="text, record">
          <span style="color:red">{{ record.payMoney }}</span>
        </div>

        <!-- 报名类型 -->
        <div slot="registerType" slot-scope="text, record">
          {{ RegisterTypeEnum[text] }}
          <div>{{ record['createTime'] }}</div>
        </div>
        <!-- 代报名信息 -->
        <div slot="gmatInfo" slot-scope="text, record">
          <div>{{ record.gmatName }}</div>
          <div>{{ record.gmatPhone }}</div>
        </div>

        <!-- 签到状态 -->
        <span slot="signStatus" slot-scope="text">
          {{ text === signStatusEnum.END ? '是' : '否' }}
        </span>

        <!-- 手写签名 -->
        <span slot="signImg" slot-scope="text">
          <viewer v-if="text" :images="[text]">
            <img :src="text" style="width: 30px; height: 30px" alt="" />
          </viewer>
          <span v-else>--</span>
        </span>

        <!-- 参会证 -->
        <span slot="attendanceCardUrl" slot-scope="text">
          <viewer v-if="text" :images="[text]">
            <img :src="text" style="width: 30px; height: 30px" alt="" />
          </viewer>
          <span v-else>--</span>
        </span>

        <!-- 活动安排 -->
        <template slot="activityArrangeList" slot-scope="text, record">
          <a-popover v-if="record.activityArrangeList && record.activityArrangeList.length" placement="top">
            <template slot="content">
              <div v-for="(item, index) in record.activityArrangeList" :key="index">
                <span>{{ item.name }}</span>
                <span class="_ml-10">{{ item.displayName }}</span>
              </div>
            </template>
            <div
              v-for="(item, index) in record.activityArrangeList"
              :key="index"
              style="overflow: hidden; text-overflow: ellipsis"
            >
              {{ item.name }} {{ item.displayName }}
            </div>
          </a-popover>
        </template>

        <!-- 状态 -->
        <span slot="approvalStatus" slot-scope="text, record">
          <DictTag :options="Dict.getLocal('rosterApprovalStatusDict')" :value="record.approvalStatus" />
        </span>
        <!-- 状态 -->
        <span slot="verifyInfo" slot-scope="text, record">
          <div>{{ record['verifyName'] }}</div>
          <div>{{ record['verifyTime'] }}</div>
        </span>

        <span slot="inviteUserName" slot-scope="text, record">
          <div>{{ record.inviteUserPhone }}</div>
          <div>{{ record.inviteUserName }}</div>
        </span>

        <!-- 参会者标签 -->
        <template slot="labelDtoList" slot-scope="text, record">
          <TableTagList :tagList="resetTagList(record)" closable @close="tag => handleDelLabel(record.id, tag.id)" />
        </template>

        <span slot="signInfo" slot-scope="text, record">
          <div>
            {{ signOperatorAndCheckType(record['signType']) }}
          </div>
          <div>
            {{ record['signTime'] }}
          </div>
        </span>

        <!-- 操作 -->
        <div slot="actionFilterIcon" class="disFlxAC min-width-12">
          <CustomTable :name="$route.name + '_' + titleKey" :columns="columns" :newColumns="newColumns" />
        </div>
        <template slot="actionFilter">
          <div></div>
        </template>
        <span slot="action" slot-scope="text, record">
          <ButtonGroup
            :max-length="2"
            :key="`${record.signStatus}-${record.approvalStatus}-${activityInfo.activityType}`"
          >
            <a-button
              v-for="item in _btnList(record)"
              :key="item.text"
              :type="item.type || 'primary'"
              :ghost="item.text === '审核' ? false : true"
              size="small"
              class="width-8"
              @click="item.fn"
            >
              {{ item.text }}
            </a-button>
          </ButtonGroup>
        </span>
      </s-table>
    </a-spin>

    <!-- 选用户代报名 -->
    <NotRegisteredUser ref="NotRegisteredUser" />

    <YesRegisteredUser ref="YesRegisteredUser" />

    <!-- 导入代报名名单弹窗 -->
    <ImportRegistration
      ref="importRegistration"
      :activityId="activityId"
      :activityInfo="activityInfo"
      @success="refresh(false, 'emit')"
    />

    <!-- 批量打标签弹窗 -->
    <SetLabel
      ref="setLabel"
      :activityId="activityId"
      :isBranch="isBranch"
      :selectedRows="selectedRows"
      :label_list="label_list"
      @refreshLabel="getLabelList"
      @branchLabelAddSuccess="branchLabelAddSuccess"
    />

    <!-- 新增报名-自定义表单 -->
    <UserCustomFormModal
      ref="userCustomFormModal"
      :activityId="activityId"
      :activityInfo="activityInfo"
      @success="refresh(false, 'emit')"
      @openSetLabel="handleSetSingleLabel"
    />

    <!-- 导出报名名单 -->
    <TaskNotification ref="TaskNotification" />

    <!-- 代签到 -->
    <SignTypeModal
      ref="signTypeModal"
      :registerId="registerId"
      :registerName="record.personName"
      :activityId="activityId"
      @signSuccess="refresh(false, 'emit')"
    />

    <!-- 打印胸卡（单个） -->
    <PrintBadge
      ref="printBadge"
      :activityId="activityId"
      :registerId="registerId"
      :record="record"
      @ok="refresh(false, 'emit')"
    />

    <!-- 打印胸卡（批量） -->
    <PrintBadgeBatch
      ref="printBadgeBatch"
      :selectedRows="selectedRows"
      :activityId="activityId"
      @ok="handlePrintBadgeBatchSuccess"
    />
    <ChooseTicket ref="chooseTicketRef" @ok="showNotRegisteredUser" />
  </a-card>
</template>

<script>
import { STable } from '@/components'
import NotRegisteredUser from '@/components/ChooseUser/NotRegisteredUser'
import ImportRegistration from '@/views/activity/components/importRegistration'
import SetLabel from '@/views/activity/components/userTags/setLabel.vue'
import UserCustomFormModal from '@/views/activity/components/customFormModal/index.vue'
import SignTypeModal from '@/views/activity/components/signManage/signTypeModal.vue'
import PrintBadge from '@/views/activity/components/printBadge/printBadge.vue'
import PrintBadgeBatch from '@/views/activity/components/printBadge/printBadgeBatch.vue'
import ChooseTicket from '@/components/ChooseTicket/index.vue'
import YesRegisteredUser, { ActionType } from '@/components/ChooseUser/YesRegisteredUser'
import { memberLevelGetDownList } from '@/api/system/system'
import { debounce } from '@/utils/common'
import CustomTable from '@/components/Cuscolumn'
import {
  signStatusEnum,
  signTypeEnum,
  TicketTypeEnum,
  RosterApprovalStatusEnum,
  publishStatusEnum
} from '@/enums/activity'
import Vue from 'vue'
import { TENANTID } from '@/store/mutation-types'
import {
  rosterList,
  cancelRegistration,
  anewRegistration,
  updateAttendanceCard,
  getActivityLabelList,
  labelDel,
  getActivityInfo,
  activityRegisterExport,
  selectAllActivityRegister,
  activityRegisterDel,
  getActivityOrganization,
  getTicketList,
  cancelRegistrationBatch,
  queryNotRegistration,
  batchRegistration,
  registerInfoByIds
} from '@/api/activity/activity'
import { RegisterTypeEnum, activityTypeEnum, ActivitySettlementStatusEnum } from '@/enums/activity'
import moment from 'moment'
import TaskNotification from '@/components/tools/TaskNotification'
import SendMessageSelect from '@/views/operations/message/components/sendMessageSelect'
import { DataSourceEnum } from '@/enums/member'
import TableTagList from '@/views/member/grouping/components/tableTagList'
import DictTag from '@/components/DictTag'
import ButtonGroup from '@/components/Table/buttonGroup'
import SelectCustomForm from '@/components/selectCustomForm'
import { allNotRegistrationIds } from '@/api/activity/enroll'
import registerBatchVerify from '@/views/activity/mixins/registerBatchVerify'
import cancelRegisterBatch from '@/views/activity/mixins/cancelRegisterBatch'
import UserIconAction from '@/views/activity/components/UserIconAction/index.vue'
import SetMember from '@/views/activity/components/SetMember/index.vue'
var targetWindow
export default {
  props: ['signStatus', 'approvalStatus', 'titleKey', 'inviteAppUserInfoId'],
  mixins: [registerBatchVerify, cancelRegisterBatch],
  components: {
    ChooseTicket,
    STable,
    NotRegisteredUser,
    ImportRegistration,
    SetLabel,
    UserCustomFormModal,
    CustomTable,
    TaskNotification,
    SendMessageSelect,
    TableTagList,
    DictTag,
    SignTypeModal,
    PrintBadge,
    PrintBadgeBatch,
    ButtonGroup,
    SelectCustomForm,
    YesRegisteredUser,
    UserIconAction,
    SetMember
  },
  data() {
    return {
      DataSourceEnum,
      activityTypeEnum,
      TicketTypeEnum,
      tenantId: Vue.ls.get(TENANTID),
      // 查询参数
      activityId: '',
      memberLevelOption: [],
      activityInfo: {}, // 活动详情,

      // 审核表单
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
          width: 60
        },
        {
          title: '报名者信息',
          scopedSlots: { customRender: 'personInfo' },
          width: 200
        },
        { title: '单位信息', scopedSlots: { customRender: 'companyInfo' }, width: 200 },
        {
          title: '身份信息',
          scopedSlots: { customRender: 'sourceInfo' },
          width: 170
        },
        {
          title: '报名类型',
          scopedSlots: { customRender: 'ticketName' },
          width: 200
        },
        {
          title: '实付金额（元）',
          scopedSlots: { customRender: 'payMoney' },
          width: 120
        },
        { title: '状态', scopedSlots: { customRender: 'approvalStatus' }, width: 100 },
        { title: '邀约人', scopedSlots: { customRender: 'inviteUserName' }, width: 150 },
        {
          title: '报名信息',
          dataIndex: 'registerType',
          scopedSlots: { customRender: 'registerType' },
          width: 150
        },
        { title: '提交人信息', scopedSlots: { customRender: 'gmatInfo' }, width: 100 },
        {
          title: '参会者标签',
          dataIndex: 'labelDtoList',
          width: 220,
          scopedSlots: { customRender: 'labelDtoList' }
        },
        {
          title: '审核信息',
          width: 150,
          ellipsis: true,
          scopedSlots: { customRender: 'verifyInfo' }
        },
        {
          title: '签到信息',
          width: 220,
          scopedSlots: { customRender: 'signInfo' }
        },
        {
          title: '手写签名',
          dataIndex: 'signImg',
          width: 100,
          scopedSlots: { customRender: 'signImg' }
        },
        {
          title: '活动安排',
          dataIndex: 'activityArrangeList',
          width: 200,
          scopedSlots: { customRender: 'activityArrangeList' },
          ellipsis: true
        },
        // {
        //   title: '参会证',
        //   dataIndex: 'attendanceCardUrl',
        //   scopedSlots: { customRender: 'attendanceCardUrl' },
        //   width: 100
        // },
        { title: '备注', dataIndex: 'remarks', width: 150, ellipsis: true },
        { title: '信息收集内容', dataIndex: 'itemValue', width: 150, ellipsis: true },
        {
          title: '操作',
          scopedSlots: {
            customRender: 'action',
            filterDropdown: 'actionFilter',
            filterIcon: 'actionFilterIcon'
          },
          width: 250,
          fixed: 'right'
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10
      },
      total: 0,
      loadData: parameter => {
        this.pagination.current = parameter.current
        this.pagination.pageSize = parameter.pageSize
        return rosterList(
          Object.assign(parameter, this.queryParam, {
            activityId: this.activityId,
            isNullPhone: this.queryParam.isNullPhone ? 1 : 0,
            signStatus: this.signStatus || this.queryParam.signStatus,
            approvalStatus: this.approvalStatus || this.queryParam.approvalStatus,
            orderByColumn: this.approvalStatus ? 'createTime' : this.signStatus ? 'signTime' : '',
            inviteAppUserInfoId: this.inviteAppUserInfoId
          })
        ).then(res => {
          this.firstLoad = true
          this.total = res.data.total
          return res
        })
      },
      queryParam: {
        keyWord: undefined,
        levelId: undefined,
        registerType: undefined,
        approvalStatus: undefined,
        identity: undefined,
        signStatus: undefined,
        labelIds: [],
        isNullPhone: 0,
        sourceTenantId: undefined
      },
      RegisterTypeEnum,
      signStatusOptions: [
        { text: '已签到', value: signStatusEnum.END },
        { text: '未签到', value: signStatusEnum.STAY }
      ],
      ticketList: [],
      memberLevelOptions: [],
      label_list: [],
      organizationList: [],
      registerId: undefined,
      loading: false,
      isBranch: false,
      firstLoad: false,
      drd: {
        member_level_list: []
      },
      editUserType: 'add',
      record: {},
      selectedRows: [],
      signStatusEnum,
      signTypeEnum,

      itemList: []
    }
  },
  watch: {
    firstLoad(val) {
      val &&
        setTimeout(() => {
          this.$forceUpdate()
        }, 300)
    }
  },
  computed: {
    isOneself() {
      return this.activityInfo.activityType === activityTypeEnum.oneself
    },
    newColumns() {
      const currentColumns = this.$store.state.user.customTable
      if (currentColumns && currentColumns[this.$route.name + '_' + this.titleKey]) {
        return this.$options
          .data()
          .columns.filter(v => {
            const _items = currentColumns[this.$route.name + '_' + this.titleKey].find(
              item => item === v.title || item.title === v.title
            )
            if (_items) return Object.assign(v, _items)
          })
          .sort((a, b) => {
            return a.tableSort - b.tableSort
          })
      } else {
        return this.columns
      }
    },
    disableOption() {
      return [
        ActivitySettlementStatusEnum.PROGRESS,
        ActivitySettlementStatusEnum.SUCCESS,
        ActivitySettlementStatusEnum.PART_SUCCESS
      ].includes(this.activityInfo.settleStatus)
    },
    registerTypeList() {
      let list = []
      Object.keys(RegisterTypeEnum).forEach(k => {
        list.push({
          text: RegisterTypeEnum[k],
          value: k
        })
      })
      return list
    }
  },
  created() {
    const _this = this
    targetWindow = window.opener || {}
    const { location } = targetWindow
    if (location && location.pathname === '/activity/activitySeatingPlan' && _this.$route.query.openApply) {
      this.activityId = _this.$route.query.openApply
    } else {
      this.activityId = this.$route.query.activityId
    }
    this.getInfo()
    this.resetFields()
    this.getLabelList()
    this.getOrganizationList()
    this.handelTicketListDownList()
    this.handelMemberLevelGetDownList()
  },
  methods: {
    debounce,
    moment,
    handelMemberLevelGetDownList() {
      memberLevelGetDownList().then(res => {
        this.memberLevelOption = res.data
      })
    },
    handleBathExamine() {
      this.$refs.YesRegisteredUser.moduleShow({
        row: this.activityInfo,
        apiList: rosterList,
        apiIdList: selectAllActivityRegister,
        apiIdSearchList: registerInfoByIds,
        approvalStatus: RosterApprovalStatusEnum.WAITING_FOR_APPROVAL,
        okText: '批量通过',
        title: '批量审核报名',
        rejectText: '批量驳回',
        disabledFn: record => {
          this.$set(record, 'disabled', record.approvalStatus !== RosterApprovalStatusEnum.WAITING_FOR_APPROVAL)
        },
        submit: async (selectedRecords, type) => {
          return new Promise((resolve, reject) => {
            this.batchVerify({
              title: '批量报名审核',
              okText: '确定驳回',
              activityUnionId: this.activityId,
              status:
                type === ActionType.APPROVED ? RosterApprovalStatusEnum.APPROVED : RosterApprovalStatusEnum.REJECTED,
              cancelText: '取消',
              ids: selectedRecords.map(item => item.id),
              callback: () => {
                this.$refs.YesRegisteredUser.closeModal()
                this.refresh(false)
                resolve()
              }
            })
          })
        }
      })
    },
    signOperatorAndCheckType(text) {
      const checkType = this.Dict.getLocal('CheckTypeEnumDict').find(item => item.dictValue == text)
      if (!checkType) return ''
      return checkType.dictLabel
    },
    resetFields() {
      Object.keys(this.queryParam).forEach(k => {
        this.queryParam[k] = undefined
      })
      this.firstLoad = false
    },
    handleReset() {
      this.$refs.SelectCustomForm.resetData()
      this.resetFields()
      this.refresh(false)
    },
    refresh(isRefresh = false) {
      const customFormItem = this.$refs.SelectCustomForm.getQueryParams()
      this.$set(this.queryParam, 'itemId', customFormItem ? customFormItem.itemId : undefined)
      this.$set(this.queryParam, 'itemAnswerId', customFormItem ? customFormItem.itemAnswerId : undefined)
      this.$set(this.queryParam, 'itemValue', customFormItem ? customFormItem.itemValue : undefined)
      this.$refs.table.refresh(isRefresh)
      this.$emit('refresh')
    },
    // 获取活动详情
    async getInfo() {
      const { data } = await getActivityInfo(this.activityId)
      this.activityInfo = data
    },

    handelTicketListDownList() {
      return getTicketList(this.activityId).then(res => {
        if (res.code === 0) {
          this.ticketList = res.data || []
        }
      })
    },
    //获取标签列表
    async getLabelList() {
      let res = await getActivityLabelList(this.activityId)
      this.label_list = res.data || []
    },
    getOrganizationList() {
      getActivityOrganization(this.activityId).then(res => {
        this.organizationList = res.data
      })
    },
    async exportTable() {
      debounce(() => {
        activityRegisterExport({
          activityId: this.activityId,
          ...this.queryParam,
          fullPath: this.$route.fullPath,
          isNullPhone: this.queryParam.isNullPhone ? 1 : 0,
          signStatus: this.signStatus || this.queryParam.signStatus,
          approvalStatus: this.approvalStatus || this.queryParam.approvalStatus,
          orderByColumn: this.approvalStatus ? 'createTime' : this.signStatus ? 'signTime' : '',
          inviteAppUserInfoId: this.inviteAppUserInfoId
        }).then(res => {
          const { data } = res
          this.$refs.TaskNotification.toggleTask(data)
        })
      })
    },
    handleBatchModule() {
      this.$refs.chooseTicketRef.moduleShow(this.activityInfo.id)
    },
    showNotRegisteredUser(activityTicketId) {
      this.$refs.NotRegisteredUser.moduleShow({
        row: this.activityInfo,
        activityTicketId,
        apiList: queryNotRegistration,
        apiIdList: allNotRegistrationIds,
        okText: '立即报名',
        disabledFn: record => {
          this.$set(record, 'disabled', record.isRegister == 1)
        },
        submit: async selectedRecords => {
          const params = selectedRecords
            .filter(f => f.isRegister !== 1)
            .map(item => {
              return {
                phoneNumber: item.phonenumber,
                memberId: item.memberId,
                activityId: this.activityId,
                activityTicketId,
                avatar: item.avatar,
                personName: item.leadingName,
                companyName: item.companyName,
                companyPosition: item.companyPosition,
                appUserInfoId: item.id
              }
            })
          if (!params.length) {
            this.$message.warning('请选择报名人员')
            return Promise.reject('请选择报名人员')
          }
          const res = await batchRegistration(params)
          if (res.code) return Promise.reject('请求失败')
          this.$message.success('报名成功')
          this.refresh(false, 'emit')
          this.sendPostMessage()
        }
      })
    },

    // 代签到
    handleSign(record) {
      this.registerId = record.id
      this.record = record
      this.$refs.signTypeModal.moduleShow(this.record)
    },
    handleCancelRoster(id) {
      this.batchCancel({
        title: '取消报名',
        ids: [id],
        callback: () => {
          this.$message.success(`取消报名成功`)
          this.refresh(false)
        }
      })
    },
    handleAgainRoster(id) {
      var _this = this
      this.$confirm({
        title: '重新报名?',
        content: '是否确定重新报名?',
        onOk() {
          anewRegistration(id).then(res => {
            if (res.code === 0) {
              _this.$message.success(`重新报名成功`)
              _this.refresh(false, 'emit')
            } else {
              _this.$message.error(res.msg)
            }
          })
        },
        onCancel() {}
      })
    },

    /** 打印胸卡（单个） */
    printBadge(row) {
      this.registerId = row.id
      this.record = row
      this.isBranch = false
      this.$refs.printBadge.openModel()
    },
    //更新参会证
    async handleUpdateAttendanceCard() {
      this.loading = true
      await updateAttendanceCard(this.activityId)
      this.$message.success('更新成功')
      this.loading = false
    },
    //导入代报名名单
    handleImportRegistration() {
      this.$refs.importRegistration.moduleShow()
    },

    //批量打印胸卡
    handlePrintBadgeBatch() {
      this.$refs.YesRegisteredUser.moduleShow({
        row: this.activityInfo,
        apiList: rosterList,
        apiIdList: selectAllActivityRegister,
        apiIdSearchList: registerInfoByIds,
        okText: '批量打胸卡',
        title: '选择需要批量打胸卡的人员',
        approvalStatus: RosterApprovalStatusEnum.APPROVED,
        disabledFn: record => {
          this.$set(record, 'disabled', record.approvalStatus != RosterApprovalStatusEnum.APPROVED)
        },
        submit: async selectedRecords => {
          return new Promise((resolve, reject) => {
            if (!selectedRecords.length) {
              this.$message.warning(`选择需要批量打胸卡的人员`)
              reject(new Error('选择需要批量打胸卡的人员'))
              return
            }
            this.isBranch = true
            this.selectedRows = selectedRecords
            this.$refs.printBadgeBatch.openModel()
            resolve()
          })
        }
      })
    },
    handlePrintBadgeBatchSuccess() {
      this.$refs.YesRegisteredUser.closeModal()
      this.refresh(false)
    },
    //批量打标签
    handleSetLabel() {
      this.$refs.YesRegisteredUser.moduleShow({
        row: this.activityInfo,
        apiList: rosterList,
        apiIdList: selectAllActivityRegister,
        apiIdSearchList: registerInfoByIds,
        okText: '批量打标签',
        title: '选择需要批量打标签的人员',
        approvalStatus: RosterApprovalStatusEnum.APPROVED,
        disabledFn: record => {
          this.$set(record, 'disabled', record.approvalStatus != RosterApprovalStatusEnum.APPROVED)
        },
        submit: async selectedRecords => {
          return new Promise((resolve, reject) => {
            if (!selectedRecords.length) {
              this.$message.warning(`请选择需要批量打标签的人员`)
              reject(new Error('请选择需要批量打标签的人员'))
              return
            }
            this.isBranch = true
            this.selectedRows = selectedRecords
            this.$refs.setLabel.moduleShow()
            resolve()
          })
        }
      })
    },
    branchLabelAddSuccess() {
      this.$refs.YesRegisteredUser.closeModal()
      this.refresh(false)
    },
    handleBathCancelRigster() {
      this.$refs.YesRegisteredUser.moduleShow({
        row: this.activityInfo,
        apiList: rosterList,
        apiIdList: selectAllActivityRegister,
        apiIdSearchList: registerInfoByIds,
        okText: '取消报名',
        cancelText: '关闭',
        title: '选择需要取消报名的人员',
        approvalStatus: RosterApprovalStatusEnum.APPROVED,
        signStatus: signStatusEnum.STAY,
        disabledFn: record => {
          this.$set(record, 'disabled', record.approvalStatus != RosterApprovalStatusEnum.APPROVED)
        },
        submit: async selectedRecords => {
          this.batchCancel({
            title: '批量取消报名',
            ids: selectedRecords.map(item => item.id),
            callback: () => {
              this.$message.success(`批量取消报名成功`)
              this.$refs.YesRegisteredUser.closeModal()
              this.refresh(false)
            }
          })
        }
      })
    },
    //设置单个报名人标签
    handleSetSingleLabel(row) {
      this.selectedRows = [row]
      this.isBranch = true
      this.$refs.setLabel.moduleShow()
    },

    //删除单个标签
    async handleDelLabel(registerId, labelId) {
      await labelDel(registerId, labelId)
      this.$message.success('删除成功')
      this.refresh(false)
    },
    //新增报名信息
    handleAdd() {
      this.$refs.userCustomFormModal.openModal({}, 'add')
    },
    //编辑报名人信息
    handleEdit(row) {
      this.$refs.userCustomFormModal.openModal(row, 'edit')
    },
    // 审核报名人信息
    handleOpenApproval(row) {
      this.$refs.userCustomFormModal.openModal(row, 'audit')
    },

    //会员代报名成功发送通知
    sendPostMessage() {
      targetWindow.postMessage && targetWindow.postMessage('Refresh', `${window.origin}/activity/activitySeatingPlan`) // 通知排座页面刷新列表
    },

    // 重置标签对象,用于统一显示
    resetTagList(row) {
      if (!row.labelDtoList) return []
      return row.labelDtoList.map(v => {
        return { id: v.labelId, tagName: v.labelName }
      })
    },
    handleDel(id) {
      var _this = this
      this.$confirm({
        title: `确定删除该报名信息？`,
        onOk: async () => {
          await activityRegisterDel(id)
          _this.$message.success(`删除成功`)
          _this.refresh(false, 'emit')
        },
        onCancel() {}
      })
    },
    _btnList(record) {
      const isCoOrganizer = this.activityInfo.activityType === activityTypeEnum.other_join // 协办方
      let oldList = [
        {
          // 协办方只能看到自己的报名数据,可以直接编辑,主办方可以看到所有的报名数据,但是只能编辑自己的
          show: isCoOrganizer ? true : record.tenantId == this.tenantId,
          text: '编辑',
          fn: () => this.handleEdit(record)
        },
        {
          show: !isCoOrganizer && record.approvalStatus === RosterApprovalStatusEnum.WAITING_FOR_APPROVAL,
          ghost: false,
          text: '审核',
          fn: () => this.handleOpenApproval(record)
        },
        {
          show:
            !isCoOrganizer &&
            record.signStatus === signStatusEnum.STAY &&
            record.approvalStatus === RosterApprovalStatusEnum.APPROVED,
          text: '代签到',
          fn: () => this.handleSign(record)
        },
        {
          show: !isCoOrganizer && record.approvalStatus === RosterApprovalStatusEnum.APPROVED,
          text: '打印胸卡',
          fn: () => this.printBadge(record)
        },
        {
          show: (() => {
            if (this.disableOption) return false
            return (
              record.approvalStatus === RosterApprovalStatusEnum.APPROVED && record.signStatus !== signStatusEnum.END
            )
          })(),
          text: '取消报名',
          fn: () => this.handleCancelRoster(record.id)
        },
        {
          show: record.approvalStatus === RosterApprovalStatusEnum.APPROVED,
          text: '打标签',
          fn: () => this.handleSetSingleLabel(record)
        },
        {
          show:
            record.approvalStatus === RosterApprovalStatusEnum.CANCELLED
              ? isCoOrganizer
                ? true
                : record.tenantId == this.tenantId
              : false,
          text: '重新报名',
          fn: () => this.handleAgainRoster(record.id)
        },
        {
          show: (() => {
            if (record.tenantId != this.tenantId) return false
            if (RegisterTypeEnum[record.registerType] != RegisterTypeEnum.batch) return false
            if (record.signStatus == signStatusEnum.END) return false
            return true
          })(),
          text: '删除',
          type: 'danger',
          fn: () => this.handleDel(record.id)
        },
        {
          show: true,
          text: '详情',
          fn: () =>
            this.$router.push({
              path: 'registrationDetail',
              query: {
                activityId: this.activityId,
                id: record.id
              }
            })
        }
      ]
      return oldList.filter(v => v.show)
    }
  },
  provide() {
    return {
      drd: () => this.drd
    }
  }
}
</script>

<style lang="less" scoped>
.text-ellipsis {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.companyInfoTag {
  display: inline-block;
  background: #e8f7ff;
  color: #3491fa;
  padding: 1px 8px;
  border-radius: 2px;
}

.ant-tag {
  white-space: normal;
}
</style>
